var express = require('express');
var router = express.Router();
var { dayPlanModel } = require("../module/plan")

// 测试数据
router.get('/test', async (req, res) => {
    let data = await dayPlanModel.find()
    res.send(data)
});

// 添加日计划
router.post('/addDayPlan', async (req, res) => {
    let query = req.body
    await dayPlanModel.create(query)
    res.send({ code: 201, msg: '添加成功' })
});

// 搜索
router.get('/searchTest', async (req, res) => {
    let searchText = req.query.searchText
    let reg = new RegExp(searchText, 'i')
    data = await dayPlanModel.find({ theme: reg })
    res.send({
        data,
        code:201,
        msg:"查询成功"
    })
})

// 分页
router.get('/pageList', async (req, res) => {
    let pageIndex = req.query.pageIndex
    let pageSize = req.query.pageSize
    let data = ''
    let total = 0
    data = await dayPlanModel.find().limit(pageSize).skip((pageIndex - 1) * pageSize).exec()
    total = await dayPlanModel.count()
    res.send({
        msg: "查询成功",
        data,
        total
    })
})

// 分页+搜索
router.get('/searchPageList', async (req, res) => {
    let pageIndex = req.query.pageIndex
    let pageSize = req.query.pageSize
    let searchText = req.query.searchText
    let data = ''
    let total = 0
    let reg = new RegExp(searchText, 'i')
    if (searchText) {
        data = await dayPlanModel.find({ theme: reg }).limit(pageSize).skip((pageIndex - 1) * pageSize).exec()
        let pageList = await dayPlanModel.find({ theme: reg })
        total = pageList.length
    } else {
        data = await dayPlanModel.find().limit(pageSize).skip((pageIndex - 1) * pageSize).exec()
        total = await dayPlanModel.count()
    }
    res.send({
        msg: "查询成功",
        data,
        total
    })
})


// 修改日计划
router.put('/editDayPlan', async (req, res) => {
    await dayPlanModel.updateOne({ _id: req.body._id }, req.body)
    let data = await dayPlanModel.find()
    res.send({
        code: 201,
        msg: "修改成功",
        data
    })
})

// 删除日计划
router.delete('/deleteDayPlan', async (req, res) => {
    await dayPlanModel.deleteOne({ _id: req.body._id })
    res.send({
        code: 201,
        msg: "删除成功"
    })
})



module.exports = router;